<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Accounts Manager</title>
        <meta name="description" content="The HTML5 Herald">
        <meta name="author" content="SitePoint">

        <!--[if lt IE 9]>
            <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>
    <body style="width: 75%; margin: 0px auto; padding-top: 200px;">
        <!-- the welcome HTML -->
        <h1>ethereumjs-accounts</h1>
        <p>Welcome to the ethereumjs-accounts demo. Here you can generate, encrypt, store, and remove Ethereum accounts in browser.</p>
        <br><br>
        
        <!-- account generator HTML -->
        <h2>Generate Account</h2>
        <p>Here you can generate an Ethereum account in browser, optionally you can encrypt the account private and public keys with a passphrase using AES encryption.</p>
        <input type="text" placeholder="passphrase" id="new_passphrase"> 
        <hr>
        <button id="new">Generate Account</button>
        <br>
        <pre id="new_result"></pre>
        
        <br><br>
        
        <!-- get accounts HTML -->
        <h2>Get Accounts</h2>
        <p>Here you can get an Ethereum account from browser storage. If the account uses encryption, provide the passphrase below. You can get all accounts by leaving the address field blank.</p>
        <input type="text" placeholder="address" id="get_address"> 
        <input type="text" placeholder="passphrase" id="get_passphrase"> 
        <hr>
        <button id="get">Get Account</button>
        <button id="selected">Get Selected</button>
        <br>
        <pre id="get_result"></pre>
        
        <br><br>
        
        <!-- clear accounts HTML -->
        <h2>Clear Accounts</h2>
        <p>Here you can clear all Ethereum accounts stored in browser storage.</p>
        <hr>
        <button id="clear">Clear Accounts</button>
        <br>
        <pre id="clear_result"></pre>
        
        <br><br>
        
        <!-- backup accounts HTML -->
        <h2>Backup Accounts</h2>
        <p>Here you can save your current browser wallet in a zip file.</p>
        <hr>
        <button id="backup">Backup Wallet</button>
        <br>
        <pre id="backup_result"></pre>
        
        <br><br>
        
        <!-- backup accounts HTML -->
        <h2>Import/Export Accounts</h2>
        <p>Here you can export your accounts as a JSON ready string object, or import a JSON ready string object that contains account objects. Importing accounts will override existing stored accounts with the same addresses.</p>
        <textarea id="importInput" onClick="this.setSelectionRange(0, this.value.length)" ></textarea>
        <hr>
        <button id="import">Import Accounts</button>
        <button id="export">Export Accounts</button>
        <br>
        <pre id="import_result"></pre>
        
        <br><br>
        
        <!-- Mulitply Contract Example -->
        <h2>Deploy/Use Multiply Contract</h2>
        <p>Here you can deploy a contract and interact with it from a account you created in browser.</p>
        <input type="text" placeholder="from address" id="multiply_fromAddress">
        <textarea id="multiplyValue" placeholder="Multiply Value"></textarea>
        <hr>
        <button id="deploy">Deploy Contract</button>
        <button id="multiply">Multiply</button>
        <br>
        <pre id="multiplyResult"></pre>
        
        <br><br>
        
        <!-- some web3 HTML -->
        <h2>Use with Web3</h2>
        <p>First off, here are the accounts you have stored in geth: </p>
        <p id="web3Accounts"></p>
        
        <p>Here you can use an account stored in browser to send a transaction with the web3.js object. This is an example use case where Accounts.extendWeb3 method is used to extend the web3.js object. Make sure you send Ether to the account you want to use. The value below will be converted to ether.</p>
        <input type="text" placeholder="from address" id="web3_fromAddress"> 
        <input type="text" placeholder="to address" id="web3_toAddress"> 
        <input type="text" placeholder="value (e.g. 1 [ether])" id="web3_value">
        <hr>
        <button id="send">Send Transaction</button>
        <br>
        <pre id="web3_result"></pre>
        
        <br><br>
        
        <!-- ethereumjs-accounts JS -->
        <script src="../dist/ethereumjs-accounts.js"></script>
        <script src="web3.js"></script>
        <script src="hooked-web3-provider.js"></script>
        <script type="text/javascript">
            // Make alias of docuemtn.getElementById -> $
            function makeAlias(object, name) {
                var fn = object ? object[name] : null;
                if (typeof fn == 'undefined') return function () {}
                return function () {
                    return fn.apply(object, arguments)
                }
            }
            
            // Make docuemtn.getElementById aliased by $
            $ = makeAlias(document, 'getElementById');
            
            // Create Accounts Object
            var Accounts = new Accounts();
            
            // Set web3 provider
            var provider = new HookedWeb3Provider({
              host: "http://localhost:8545",
              transaction_signer: Accounts
            });
            web3.setProvider(provider);
            
            // Extend the web3 object
            Accounts.log = function(msg){console.log(msg);};
            
            console.log(Accounts.length);
            
            // When the window DOM loads
            window.onload = function () {
                // Send ether to the account you want to use (for testing)
                //web3.eth.sendTransaction({from: web3.eth.accounts[0], to: '0x6f801e7bfea263fa60a1ed1afcffd124f749ee79', value: web3.toWei(30, 'ether')}, function(err, result){console.log(err, result);});
                
                // When 'Generate Account' is clicked
                $("new").onclick = function() {
                    console.log($("new_passphrase").value);
                    
                    var newAccount = Accounts.new($("new_passphrase").value);
                    $("new_result").innerHTML = JSON.stringify(newAccount, null, 2);
                };
                
                // When 'Get Accounts' is clicked
                $("get").onclick = function() {
                    $("get_result").innerHTML = JSON.stringify(
                        Accounts.get(
                        $("get_address").value
                        , $("get_passphrase").value
                    ), null, 2);
                };
                
                // When 'Get Selected' is clicked
                $("selected").onclick = function() {
                    $("get_result").innerHTML = JSON.stringify(
                        Accounts.get(
                        'selected'
                        , $("get_passphrase").value
                    ), null, 2);
                };

                // When 'Clear' is clicked
                $("clear").onclick = function() {
                    Accounts.clear();
                    $("clear_result").innerHTML = 'Accounts cleared!';
                };

                // When 'Clear' is clicked
                $("backup").onclick = function() {
                    Accounts.backup();
                    $("backup_result").innerHTML = 'Backup created!';
                };

                // When 'Import Accounts' is clicked
                $("import").onclick = function() {
                    Accounts.import($('importInput').value);
                    $("import_result").innerHTML = 'Imported accounts.';
                };

                // When 'Clear' is clicked
                $("export").onclick = function() {
                    $('importInput').value = Accounts.export();
                    $("import_result").innerHTML = 'Exported accounts!';
                };
                
                $('web3Accounts')
                    .innerHTML = JSON.stringify(web3.eth.accounts);
                
                var source = "" +
                    "contract test {\n" +
                    "   function multiply(uint a) constant returns(uint d) {\n" +
                    "       return a * 7;\n" +
                    "   }\n" +
                    "}\n",
                    code = '6060604052602a8060116000396000f300606060405260e060020a6000350463c6888fa18114601a575b005b6007600435026060908152602090f3',
                    abi = [
                      {
                        "constant": true,
                        "inputs": [
                          {
                            "name": "a",
                            "type": "uint256"
                          }
                        ],
                        "name": "multiply",
                        "outputs": [
                          {
                            "name": "d",
                            "type": "uint256"
                          }
                        ],
                        "type": "function"
                      }
                    ],
                    myContract;
                
                function createExampleContract() {
                    // hide create button
                    document.getElementById('multiplyResult').innerText = code;
                    // let's assume that coinbase is our account
                    web3.eth.defaultAccount = web3.eth.coinbase;
                    // create contract
                    document.getElementById('multiplyResult').innerText = "transaction sent, waiting for confirmation";
                    web3.eth.contract(abi).new({from: $('multiply_fromAddress').value, data: code, gas: 300000}, function (err, contract) {
                        console.log(err, contract);
                        
                        if(err) {
                            document.getElementById('multiplyResult').innerText = 'There was an error deploying Multply contract: ' + String(err);
                            return;
                        // callback fires twice, we only want the second call when the contract is deployed
                        } else if(contract.address){
                            myContract = contract;
                            document.getElementById('multiplyResult').innerText = 'Multiply contract deployed to address: ' + myContract.address;
                        }
                    });
                };
                    
                function callExampleContract() {
                    // this should be generated by ethereum
                    var param = parseInt(document.getElementById('multiplyValue').value);
                    // call the contract
                    var res = myContract.multiply(param);
                    document.getElementById('multiplyResult').innerText = res.toString(10);
                };
                
                $('deploy').onclick = function() {
                    // solidity code code
                    createExampleContract();
                };
                
                $('multiply').onclick = function() {
                    // solidity code code
                    callExampleContract();
                };

                // When 'Send Transaciton' is clicked
                $("send").onclick = function() {
                    $("web3_result").innerHTML = 'Processing transaction...';                           
                    
                    web3.eth.getBalance(             
                        '0x16269a6af79fe24b595e458586ba1f54c24d3c80'
                    , function(err, result){
                        if(!err)
                            $("web3_result").innerHTML = 'Account has a balance of ' + String(web3.fromWei(result, 'ether')) + ' ether...';
                    });
                    
                    web3.eth.sendTransaction({
                        from: $("web3_fromAddress").value
                        , to: $("web3_toAddress").value
                        , value: web3.toWei($("web3_value").value, 'ether')
                        , gas: 300000
                    }, function(err, result){
                        var html = '';
                        
                        if(err)
                            html = 'There was an error with the transaciton: ' + String(err);
                        else
                            html = 'The transaction went through succesfully, hash: ' + String(result);
                        
                        $("web3_result").innerHTML = html;
                    });
                };
            };
        </script>
    </body>
</html>